package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"news/cache"
	"news/models"
	"news/pkg"
	"time"
)

type UserController struct {
	beego.Controller
}

type Res struct {
	Code    int         `json:"code"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
}

func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "账号或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	user := models.User{
		Username: username,
		Password: pkg.Md5(password),
	}

	if err := user.GetUserBy(); err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "系统错误",
		}
		c.ServeJSON()
		return
	}

	if user.ID > 0 {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "用户已存在",
		}
		c.ServeJSON()
		return
	}

	user.CreateUser()
	c.Data["json"] = Res{
		Code:    200,
		Data:    user,
		Message: "用户注册成功",
	}
	c.ServeJSON()
	return
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "账号或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	user := models.User{
		Username: username,
		Password: pkg.Md5(password),
	}

	key := "login" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "密码次数超过3次，封禁2小时",
		}
		c.ServeJSON()
		return
	}

	if user.ID == 0 {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code:    200,
		Data:    user,
		Message: "登录成功",
	}
	c.ServeJSON()
	return

}
